<template>
	<div class="list-wrapper">
    <div class="list-header" :style="{height:listHeaderH+'px'}">
      <div class="header-fixed">
        <!--头部搜索-->
        <head-search class="itemList-search" :is_search_button="is_search_button" v-model="postData.title" :deleteTitle="deleteTitle" @refreshFn="refreshFn"></head-search>
        <div class="searchShop" v-if="new_supplier_info.length>0">
          <div class="searchShop-box">
            <div class="item" v-for="(item,index) in new_supplier_info" :key="index" @click="NavToStore(item.link)">
              <div class="shop-log">
                <img :src="item.logo || imgError" alt="">
              </div>
              <div class="shop-info">
                <div class="shop-name">{{item.name}}</div>
                <div class="shop-detail">
                  <p class="all">全部商品{{item.store_item_num}}</p>
                  <p class="new">上新商品{{item.store_new_item_num}}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="cate">
          <van-tabs
            :ellipsis="false"
            :line-width="tabLineWidth"
            :line-height="tabLineHeight"
            v-model="activeOne"
            v-if="cateListOne && cateListOne.length > 0"
            @click="handleClickCateOne">
            <van-tab v-for="(item, index) in cateListOne" :title="item.class_name" :key="index"></van-tab>
          </van-tabs>
          <van-tabs
            :ellipsis="false"
            :line-width="tabLineWidth"
            :line-height="tabLineHeight"
            v-model="activeTwo"
            v-if="cateListTwo && cateListTwo.length > 0"
            @click="handleClickCateTwo">
            <van-tab v-for="(item, index) in cateListTwo" :title="item.class_name" :key="index"></van-tab>
          </van-tabs>
          <van-tabs
            :ellipsis="false"
            :line-width="tabLineWidth"
            :line-height="tabLineHeight"
            v-model="activeThree"
            v-if="cateListThree && cateListThree.length > 0"
            @click="handleClickCateThree">
            <van-tab v-for="(item, index) in cateListThree" :title="item.class_name" :key="index"></van-tab>
          </van-tabs>
        </div>

        <div class="sort itemList-sort" v-show="itemList.length>0">
          <div class="sort-item">
            <!--排序搜索-->
            <sort-search @item="sortSearchFn" :typeList="typeList" :listStyle="listStyle"></sort-search>
          </div>
          <!-- <div class="other-class">

          </div> -->
        </div>
      </div>
    </div>

    <div class="list-wrapper-app">

      <!--商品列表-->
      <item-wrapper :itemList="itemList" :listStyle="listStyle" :illegal_msg="illegal_msg" :otherInfo="otherInfo" :vanList="vanList" :isShowNoData="isShowNoData" @scrollReachBottom="getData"></item-wrapper>
    </div>

  </div>
</template>

<script>
/**
	 * @Author: yqe@360shop.cn
	 * @Date: 2019-10-26 18:48:09
 * @Last Modified by: zhangmeng
 * @Last Modified time: 2020-12-18 10:39:37
	 */
import Vue from 'vue'
import headSearch from './headSearch'
import sortSearch from './sortSearch'
import itemWrapper from './itemWrapper'
import { getItemList, getItemCats } from '@/api/item/item'
import { openPage } from '@/utils/utils'

import { Tab, Tabs } from 'vant'

Vue.use(Tab)
Vue.use(Tabs)

export default Vue.extend({
  name: 'index',
  components: {
    headSearch,
    sortSearch,
    itemWrapper
  },
  data() {
    return {
      imgError: 'https://img.wifenxiao.com/h5-wfx/images/default_goods_img.jpg',
      tabLineWidth: '27px',
      tabLineHeight: '2px',
      isShowNoData: false,
      activeOne: 0,
      activeTwo: 0,
      activeThree: 0,
      listHeaderH: 0,
      is_search_button: 0,
      postData: {
        title: '',
        p: 1,
        order: undefined, // priceUp,priceDown,salesDown,salesUp,newUp,newDown
        new: undefined,
        ltime: undefined,
        crowd: undefined,
        class_id: undefined,
        miao: undefined,
        cycle: undefined,
        supplier: undefined, // 供应商id
        couponId: undefined, // 优惠券id
        package: undefined,
        auction: undefined,
        id: undefined // 优惠码id
      },
      itemList: [], // 商品列表
      new_supplier_info: [],
      cateListOne: [],
      cateListTwo: [],
      cateListThree: [],
      typeList: [
        { label: '默认', active: true, type: 0, prop: 'default', sort: 'none' },
        { label: '价格', active: false, type: 1, prop: 'price', sort: '' },
        { label: '销量', active: false, type: 2, prop: 'sales', sort: '' },
        { label: '新品', active: false, type: 3, prop: 'new', sort: '' },
        // { label: '', active: false, type: 5, prop: 'listStyle', sort: 'none' }
      ],
      listStyle: true,
      otherInfo: {
        earn_alias: '',
        is_open_kuajing: '',
        is_display_original_price: '',
        cash_point_name: ''
      },
      vanList: {
        loading: false,
        error: false,
        finished: false
      },
      illegal_msg: '暂无商品数据',
      deleteTitle: ''
    }
  },
  methods: {
    // 进店逛逛
    NavToStore(link) {
      openPage(link)
    },
    // 获取顶部搜索框和分类的高度
    getHeaderFixedH(){
      document.querySelector('.header-fixed').$$getBoundingClientRect().then(res => {
        // console.log('listHeaderH',res)
        this.listHeaderH = res.height
      })
    },

    /**
     * 点击一级分类
     */
    handleClickCateOne(index) {
      const cateListOne = this.cateListOne
      if (cateListOne[index].child && cateListOne[index].child.length > 0) {
        this.cateListTwo = cateListOne[index].child
        this.cateListThree = []
      } else {
        this.cateListTwo = []
        this.cateListThree = []
      }
      this.postData.class_id = cateListOne[index].class_id || ''
      this.postData.p = 1
      this.activeTwo = 0
      this.activeThree = 0
      this.activeOne = index
      this.getItemListPost()
      this.$nextTick(()=>{
        this.getHeaderFixedH();
      })
    },
    /**
       * 点击二级分类
       */
    handleClickCateTwo(index) {
      // // console.log(index)
      const cateListTwo = this.cateListTwo
      if (cateListTwo[index].child && cateListTwo[index].child.length > 0) {
        this.cateListThree = cateListTwo[index].child
      } else {
        this.cateListThree = []
      }
      this.postData.class_id = cateListTwo[index].class_id == 0 ? this.cateListOne[this.activeOne].class_id : cateListTwo[index].class_id
      this.postData.p = 1
      this.activeThree = 0
      this.activeTwo = index
      this.getItemListPost()
      this.$nextTick(()=>{
        this.getHeaderFixedH();
      })
    },
    /**
       * 点击三级分类
       */
    handleClickCateThree(index) {
      const cateListThree = this.cateListThree
      this.postData.class_id = cateListThree[index].class_id == 0 ? this.cateListTwo[this.activeTwo].class_id : cateListThree[index].class_id
      this.postData.p = 1
      this.itemList = []
      this.getItemListPost()
    },
    /**
       * 获取商品分类
       */
    getItemCatsPost() {
      const params = {
        supplier: this.postData.supplier
      }
      getItemCats(params).then(res => {
        if (res.status === 1) {
          const class_lists = res.data.class_lists
          const obj = { class_name: '全部', class_id: 0 }
          class_lists.unshift(obj)
          this.cateListOne = class_lists
          const classId = this.$route.query.class_id
          this.cateListOne.forEach((item, index) => {
            if (classId == item.class_id) {
              this.activeOne = index
              this.cateListTwo = item.child
              this.cateListTwo.unshift(obj)
              return false
            }
            const oneIndex = index
            if (item.child && item.child.length > 0) {
              item.child.unshift(obj)
              item.child.forEach((itemtwo, indextwo) => {
                if (classId == itemtwo.class_id) {
                  this.activeOne = oneIndex
                  this.activeTwo = indextwo
                  this.cateListTwo = item.child
                  this.cateListThree = itemtwo.child
                  return false
                }
                const twoIndex = indextwo
                if (itemtwo.child && itemtwo.child.length > 0) {
                  itemtwo.child.unshift(obj)
                  itemtwo.child.forEach((itemthree, indexthree) => {
                    if (classId == itemthree.class_id) {
                      this.activeOne = oneIndex
                      this.activeTwo = twoIndex
                      this.activeThree = indexthree
                      this.cateListTwo = item.child
                      this.cateListThree = itemtwo.child
                    }
                  })
                }
              })
            }
          })
          this.$nextTick(()=>{
            this.getHeaderFixedH();
          })
        }
      })
    },
    /**
       * 获取商品列表
       */
    getItemListPost(type) {
      /* this.$loadingWrap.show() // 打开loading
        setTimeout(() => {
          this.$loadingWrap.close() // 关闭loading
        }, 150000) */
      if (this.postData.p == 1) {
        this.vanList.finished = false
        this.vanList.loading = false
        this.vanList.error = false
      }
      if (this.vanList.finished === true) {
        return false
      }
      const params = Object.assign({ sid: this.$route.query.sid }, this.postData, true)
      if (this.$route.query.distributor_apply) {
        params.distributor_apply = this.$route.query.distributor_apply
      }
      if (this.$route.query.supplierId) {
        params.supplier = this.$route.query.supplierId
      }
      // TODO 在mounted里面title已经赋值了query的title 不需要再获取了 不然会导致商品列表数据缺少
      // params.title = this.postData.title ? this.postData.title : this.$route.query.title
      // 链动产品、三三复制
      if (this.$route.query.link) {
        params.link = this.$route.query.link
        // 排队免单产品
        if (this.$route.query.activity_id) {
          params.activity_id = this.$route.query.activity_id
        }
      }
      getItemList(params).then((res) => {
        // this.$loadingWrap.close()
        this.vanList.loading = false
        if (res.status === 1) {
          // 关键词搜索
          this.illegal_msg = res.data.illegal_msg || '暂无商品数据'
          this.deleteTitle = ''
          const title = this.postData.title
          if (this.illegal_msg != '暂无商品数据') {
            this.postData.title = ''
            this.deleteTitle = title
          } 
          const resData = res.data.lists
          if (resData && resData.length <= 0) {
            if (this.$refs.waterfalls) {
              this.$refs.waterfalls.waterfallOver()
            }
            this.vanList.finished = true
          }
          resData.forEach((item) => {
            if (item.is_compress == 1) {
              item.src = `${item.pic_url}w640`
            } else {
              item.src = item.pic_url
            }
            /* if (item.pic_url.indexOf('@!') != -1) {
                item.src = `${item.pic_url}480x480`
              } else {
                item.src = item.pic_url
              } */
          })

          if (res.data) {
            if (this.postData.p == 1) {
              this.otherInfo.earn_alias = res.data.earn_alias
              this.otherInfo.is_open_kuajing = res.data.is_open_kuajing
              this.otherInfo.is_display_original_price = res.data.is_display_original_price
              this.otherInfo.point_name = res.data.point_name || '积分'
              this.otherInfo.cash_point_name = res.data.cash_point_name
              this.is_search_button = res.data.is_search_button
              this.itemList = resData
              if (this.itemList.length == 0) {
                this.isShowNoData = true
              } else {
                this.isShowNoData = false
              }

              this.$nextTick(()=>{
                this.getHeaderFixedH();
              })

            } else {
              this.itemList = this.itemList.concat(resData)
            }
            // 搜索显示供应商店铺
            if (type == 'search' || params.title) {
              this.new_supplier_info = res.data.new_supplier_info || []
            } else {
              this.new_supplier_info = []
            }
          }
          /* if (type === 'search') {
              this.itemList = resData
            } else {
              this.itemList = this.itemList.concat(resData)
            } */
        }
        // Store.saveLocal('videoList', this.itemList)
        // Store.saveLocal('videoPage', this.postData.p)
      })
    },
    /**
       * 顶部的搜索抛出
       */
    refreshFn() {
      this.postData.p = 1
      this.getItemListPost('search')
    },
    /**
       * 排序搜索
       */
    sortSearchFn(data) {
      if (data.prop == 'listStyle') {
        this.listStyle = !this.listStyle
        return false
      }
      if (data.prop == 'price') {
        this.postData.order = data.sort == 'ascending' ? 'priceUp' : 'priceDown'
      } else if (data.prop == 'sales') {
        this.postData.order = data.sort == 'ascending' ? 'salesUp' : 'salesDown'
      } else if (data.prop == 'new') {
        this.postData.order = data.sort == 'ascending' ? 'newUp' : 'newDown'
      } else if (data.prop == 'default') {
        // TODO 增加默认判断 清空order
        this.postData.order = null
      }
      // TODO 排序搜索每次都重置为1
      this.postData.p = 1
      this.getItemListPost()
    },
    /**
       * 滑到底部加载
       */
    getData() {
      this.postData.p++
      this.getItemListPost()
    },
    init() {
      this.getItemCatsPost()
      this.getItemListPost()
    },
    scrollFn() {
      document.body.$$getBoundingClientRect().then(res => {
        document.querySelector('.itemList-search').$$getBoundingClientRect().then(res1 => {
          if (res.scrollTop > this.listHeaderH - res1.height) {
            document.querySelector('.itemList-sort').style.position = 'fixed'
            document.querySelector('.itemList-sort').style.top = res1.height + 'px'
          } else {
            document.querySelector('.itemList-sort').style.position = 'relative'
            document.querySelector('.itemList-sort').style.top = 0
            if (this.listHeaderH < 100) {
              document.querySelector('.header-fixed').$$getBoundingClientRect().then(res2 => {
                this.listHeaderH = res2.height
              })
            }
          }
        })
      })
    }
  },
  created() {
    this.activeOne = this.$route.query.class_id ? this.$route.query.class_id : ''
  },
  mounted() {
    this.tabLineWidth = '0px'
    this.tabLineHeight = '0px'

    this.postData.title = this.$route.query.title
    this.postData.new = this.$route.query.new
    this.postData.ltime = this.$route.query.ltime
    this.postData.crowd = this.$route.query.crowd
    this.postData.class_id = this.$route.query.class_id
    this.postData.miao = this.$route.query.miao
    this.postData.cycle = this.$route.query.cycle
    this.postData.supplier = this.$route.query.supplier
    this.postData.couponId = this.$route.query.couponId
    this.postData.package = this.$route.query.package
    this.postData.auction = this.$route.query.auction
    this.postData.id = this.$route.query.id

    window.addEventListener('wxload', query => {
      query.supplier ? this.postData.supplier = query.supplier : ''
      this.init()
      // console.log('list wxload', query,query.search)
    })
    window.addEventListener('pullDownRefresh', () => {
      wx.stopPullDownRefresh()
      setTimeout(() => {
        this.postData.p = 1
        this.getItemListPost()
      },500)
    })
    window.addEventListener('reachbottom', () => {
      this.getData()
    })

    // 监听滚动距离 设置分类顶部距离
    this.$nextTick(() => {
      window.addEventListener('scroll', this.scrollFn)
    })
  },
  watch: {
    itemList(val) {
      // console.log(val)
      if (val.length <= 0) {
        document.getElementsByTagName('body')[0].classList.add('bg_white')
      } else {
        document.getElementsByTagName('body')[0].classList.remove('bg_white')
      }
    }
  },
  activated() {
    window.addEventListener('scroll', this.scrollFn)
  },
  deactivated() {
    window.removeEventListener('scroll', this.scrollFn) // 移除监听
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.scrollFn) // 移除监听
  }
})
</script>

<style lang="scss">
  @import 'src/styles/mixin';
  .list-wrapper{
    .van-tabs--line .van-tabs__wrap{
      height: 72px;
    }
    .van-tab{
      padding:0 30px;
      line-height: 72px;
      font-size: 26px;
      color:#333;
      flex: 0 0 auto;
      &.van-tab--active{
        font-size:28px;
        font-weight:bold;
      }
    }
    .van-tab__text--ellipsis{
      // white-space: nowrap;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    .van-tabs__line{
      background: -webkit-linear-gradient(to right,rgba(242,11,34,1),rgba(242,11,34,0.1));
      background:linear-gradient(to right,rgba(242,11,34,1),rgba(242,11,34,0.1));
    }
    .van-hairline--top-bottom, .van-hairline-unset--top-bottom{
      &::after{
        border-width: 0;
      }
    }
  }

  /* @import "src/styles/mixin";
  .list-wrapper{
    &-app{
      background: linear-gradient(to bottom, #fff, #fffeff 5%, #f5f5f5 50%, #f5f5f5);
      border-radius: 16px 16px 0 0;
    }
  } */
  .list-wrapper{
    width: 100%;
    box-sizing: border-box;
    // overflow: hidden;
    // position为sticky时 父元素overflow不能有出visible的其他属性 否则sticky会失效
    // header-fixed改为list-header布局 position改为sticky 解决小程序下拉刷新样式错乱问题
    .header-fixed{
      z-index:1003;
      width:100%;
      // background:#fff;
      padding-top: 112px;
      .itemList-search {
        width: 100%;
        position: fixed;
        top: 0;
        z-index: 101;
      }
    }
    // TODO 避免copyright计算影响 暂时这么解决
    .cate{
      padding: 0!important;
      margin: 0!important;
      min-height: 72px!important;
    }
    .sort{
      width: 100%;
      padding:10px 0;
      background:#fff;
      max-width: 750px;
      margin: 0 auto;
      z-index: 100;
    }
    //搜索结果店铺
    .searchShop{
      padding:20px 30px;
      background: #fff;
      &-box {
        display: flex;
        overflow-x: scroll;
        scrollbar-width: none; /* firefox */
        -ms-overflow-style: none; /* IE 10+ */
        &::-webkit-scrollbar {
          display: none; /* Chrome Safari */
        }
      }
      .item{
        width: 320px;
        flex-basis: 320px;
        flex-shrink: 0;
        display:flex;
        align-items:center;
        padding-bottom: 20px;
        margin-right: 20px;
        background: #F7F7F7;
        padding: 10px 12px;
        border-radius: 4px;
      }
      .shop-log{
        overflow:hidden;
        width:120px;
        height:120px;
        margin-right:14px;
        border-radius:6px;
        img{
          display:block;
          width:100%;
          height:100%;
        }
      }
      .shop-info{
        flex:1;
        .shop-name{
          width: 166px;
          font-size:24px;
          color:#333;
          font-weight: bold;
          margin-bottom: 14px;
          line-height: 32px;
          @include showEllipsis;
        }
        .shop-detail{
          font-size:20px;
          // line-height:20px;
          color:#999;
          font-weight: 500;
          line-height: 28px;
          .all {
            margin-bottom: 8px;
          }
        }
      }
      .shop-to{
        .btn{
          height:46px;
          padding:0 22px;
          border-color:#E71F19;
          font-size:24px;
          color:#F11227;
        }
      }
    }
  }
</style>
